package com.epoint.mobileoa.ui.todolist;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.bizlogic.Task;
import com.epoint.mobileoa.bizlogic.mobileoa.OpinionTask;
import com.epoint.mobileoa.db.DBHelp;
import com.epoint.mobileoa.model.OpitionTemplateAdp;
import com.epoint.mobileoa.model.OpitionTemplateAdp.ViewHolder;
import com.epoint.mobileoa.service.MainService;
import com.epoint.mobileoa.tools.LogHelp;
import com.epoint.mobileoa.tools.StringHelp;
import com.epoint.mobileoa.tools.ToastHelp;
import com.epoint.mobileoa.ui.personchoose.PersonChooseViewNew;


/**
 * @author liyc
 * @time 2012-3-14 下午3:19:02
 * @annotation 公文处理
 */

public class ProgressTaskDealView extends SuperView {

	private Button person_btn, person_btn2;// 选择下一步审批人按钮
	private Button opitionButton, cleanButton;// 意见模板按钮
	private Button deal_btn;// 提交按钮
	private String operateStatus, ShowNextActivit;
	private LinearLayout line_person, line_person2;
	private TextView task_progress, title1, title2, task_nextperson,
			task_nextperson2, task_opinion;

	private TextView step_tv;// 当前步骤
	private TextView opinion_tv;// 审批意见

	private String messageItemGuid, operatorGuid, operationGuid, workItemGuid,
			transitionGuid, pviGuid, typecode;

	public String commonopition[] = null;// 公共意见
	public String personopition[] = null;// 个人已经模版
	private OpitionTemplateAdp opitionTemplateAdp;
	private boolean[] isSelectOpition;// 初始复选情况
	private String selectOpinionText = "";// 选中已经的内容

	@Override
	public void initControls() {
		step_tv = (TextView) findViewById(R.id.step_tv);
		setTextViewFontColor(step_tv);

		opinion_tv = (TextView) findViewById(R.id.opinion_tv);
		setTextViewFontColor(opinion_tv);

		line_person = (LinearLayout) findViewById(R.id.line_person);
		line_person2 = (LinearLayout) findViewById(R.id.line_person2);

		person_btn = (Button) findViewById(R.id.person_btn);
		person_btn.setOnClickListener(this);
		person_btn2 = (Button) findViewById(R.id.person_btn2);
		person_btn2.setOnClickListener(this);

		opitionButton = (Button) findViewById(R.id.opitionButton);
		opitionButton.setOnClickListener(this);
		cleanButton = (Button) findViewById(R.id.cleanButton);
		cleanButton.setOnClickListener(this);
		task_opinion = (TextView) findViewById(R.id.task_opinion);

		deal_btn = (Button) findViewById(R.id.deal_btn);
		deal_btn.setOnClickListener(this);

		// setButtonFontColor(opitionButton);
		// setButtonFontColor(deal_btn);
		// setButtonFontColor(cleanButton);

		operateStatus = getIntent().getStringExtra("operateStatus");

		ShowNextActivit = getIntent().getStringExtra("ShowNextActivit");
		transactors = getIntent().getStringExtra("transactors");
		messageItemGuid = getIntent().getStringExtra("messageItemGuid");
		operatorGuid = getIntent().getStringExtra("operatorGuid");
		operationGuid = getIntent().getStringExtra("operationGuid");
		workItemGuid = getIntent().getStringExtra("workItemGuid");
		transitionGuid = getIntent().getStringExtra("transitionGuid");
		pviGuid = getIntent().getStringExtra("pviGuid");
		typecode = getIntent().getStringExtra("typecode");

		if (!TextUtils.isEmpty(transactors)) {
			transactors = transactors.replaceAll(";;", ";");
		}

		title1 = (TextView) findViewById(R.id.title1);
		title2 = (TextView) findViewById(R.id.title2);
		setTextViewFontColor(title1);
		setTextViewFontColor(title2);

		task_nextperson = (TextView) findViewById(R.id.task_nextperson);
		task_nextperson2 = (TextView) findViewById(R.id.task_nextperson2);
		setTextViewFontColor(task_nextperson);
		setTextViewFontColor(task_nextperson2);

		task_nextperson.setHint("请添加下一步处理人");
		task_nextperson2.setHint("请添加下一步处理人");
		task_nextperson.setEnabled(false);
		task_nextperson2.setEnabled(false);

		task_progress = (TextView) findViewById(R.id.task_progress);

		task_progress.setText(getIntent().getStringExtra("step"));
		task_progress.setTextColor(Color.RED);

		mData = new ArrayList<Map<String, Object>>();

		if (ShowNextActivit.equals("0")) {
			line_person.setVisibility(View.GONE);
			line_person2.setVisibility(View.GONE);

		} else {
			String peopleName = "";
			String peopleName2 = "";
			if (operateStatus.equals("1")) {
				line_person2.setVisibility(View.GONE);
			} else if (operateStatus.equals("2")) {
				peopleName = "送批办人员";
				peopleName2 = "送传阅人员";
				title1.setText(peopleName);
				title2.setText(peopleName2);
				task_nextperson.setHint("请添加" + peopleName);
				task_nextperson2.setHint("请添加" + peopleName2);
			} else if (operateStatus.equals("3")) {// 3 阅读
				line_person.setVisibility(View.GONE);
				line_person2.setVisibility(View.GONE);
			} else if (operateStatus.equals("4")) {
				peopleName = "转批办人员";
				peopleName2 = "转传阅人员";
				title1.setText(peopleName);
				title2.setText(peopleName2);
				task_nextperson.setHint("请添加" + peopleName);
				task_nextperson2.setHint("请添加" + peopleName2);
			} else if (operateStatus.equals("5")) {

			}

		}

		// 默认处理人设置
		if (!TextUtils.isEmpty(transactors)) {
			transactors = dealTransactors(transactors);
			String transactorsName = DBHelp.getUserDisplayNamesByGuids(this,
					transactors);
			nextpersonnames1 = transactorsName;
			nextpersonguids1 = transactors;
			task_nextperson.setText(nextpersonnames1);
		}
		doTask_GetOpinion();// 获取意见

	}

	// 对默认处理人进行去空处理
	public String dealTransactors(String transactors) {
		String temp[] = transactors.split(";");
		String string = "";
		for (int i = 0; i < temp.length; i++) {
			if (!TextUtils.isEmpty(temp[i])) {
				string += temp[i] + ";";
			}
		}
		return string;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void refresh(Object... param) {

		if (param[0].toString().equals(MainService.NORMAL)) {
			HashMap maps = (HashMap) param[1];
			String type = (String) maps.get("type");
			if (type.equals("deal")) {
				String bs = (String) maps.get("bs");
				if (bs.equals("SUCCESS")) {
					ToastHelp.showToast(this, "处理成功！");
					finish();
					ShouWenView.isdeal = true;
					FaWenView.isdeal = true;
				} else {
					ToastHelp.showToast(this, "处理失败！");
				}
				m_Dialog.dismiss();
			} else if (type.equals("opinion")) {
				if (!TextUtils.isEmpty(maps.get("bs").toString())
						&& !maps.get("bs").toString().equals(",")) {
					String opinions[] = maps.get("bs").toString().split(",");
					if (!opinions[0].equals("")) {
						commonopition = opinions[0].split(";");
					}
					if (opinions.length > 1) {
						if (!opinions[1].equals("")) {
							personopition = opinions[1].split(";");
						}
					}
					opitionButton.setEnabled(true);
				}
			}
		}
		top_pb.setVisibility(View.INVISIBLE);

	}

	@Override
	public int getLayoutInt() {
		return R.layout.taskdealprogress;
	}

	@Override
	public String setTitle() {
		return "事项处理";
	}

	private AlertDialog opinionsDialog;
	public List<Map<String, Object>> mData;
	private String transactors = "";// 默认处理人

	@Override
	public void onClick(View v) {
		if (v == person_btn) {
			resumeType = 1;
			PersonChooseViewNew.clist = StringHelp.String2List(
					nextpersonnames1, nextpersonguids1);
			String rootouguid = DBHelp.getRootOuGuid(this, fp.getUserguid());
			Intent it = new Intent(this, PersonChooseViewNew.class);
			it.putExtra("ouguid", rootouguid);
			it.putExtra("hidesearch", true);
			startActivity(it);
		} else if (v == person_btn2) {
			resumeType = 2;
			PersonChooseViewNew.clist = StringHelp.String2List(
					nextpersonnames2, nextpersonguids2);
			String rootouguid = DBHelp.getRootOuGuid(this, fp.getUserguid());
			Intent it = new Intent(this, PersonChooseViewNew.class);
			it.putExtra("ouguid", rootouguid);
			it.putExtra("hidesearch", false);
			startActivity(it);
		} else if (v == opitionButton) {
			// LayoutInflater inflater = LayoutInflater.from(this);// 渲染器
			// View customdialog2view = inflater.inflate(R.layout.customdialog2,
			// null);
			// AlertDialog.Builder builder = new AlertDialog.Builder(this);
			// builder.setIcon(R.drawable.epoint2);
			// builder.setTitle("意见模版");
			// builder.setView(customdialog2view);
			// builder.setPositiveButton("确定",
			// new DialogInterface.OnClickListener() //
			// {// 确定按钮的单击事件
			// public void onClick(DialogInterface dialog, int which) {
			// for (int i = 0; i < isSelect.length; i++) {
			// if (isSelect[i]) { // 如果该选项被选中
			// result = result + opition[i] + "、";
			// }
			// }
			// try {
			// task_opinion.setText(result.substring(0,
			// result.length() - 1));
			// } catch (Exception e) {
			// }
			// result = "";
			// }
			// });
			// builder.setNegativeButton("取消",
			// new DialogInterface.OnClickListener() {
			// public void onClick(DialogInterface dialog, int which) {
			//
			// }
			// });
			//
			// ListView listView = (ListView) customdialog2view
			// .findViewById(R.id.lv);
			// listView.setAdapter(adapter);
			// listView.setItemsCanFocus(false);
			// listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			// listView.setOnItemClickListener(new OnItemClickListener() {
			// public void onItemClick(AdapterView<?> arg0, View arg1,
			// int arg2, long arg3) {
			// ViewHolder vHollder = (ViewHolder) arg1.getTag();//
			// 在每次获取点击的item时将对于的checkbox状态改变，同时修改map的值。
			// vHollder.cBox.toggle();// 反转当前视图的选中状态
			// if (vHollder.cBox.isChecked() == true) {
			// isSelect[arg2] = true;
			// } else {
			// isSelect[arg2] = false;
			// }
			// MyAdapterCheckBox.isSelected.put(arg2,
			// vHollder.cBox.isChecked());
			//
			// }
			// });
			// opinionsDialog = builder.create();
			// opinionsDialog.show();
			showOpinion();
		} else if (v == cleanButton) {
			task_opinion.setText("");
			// for (int i = 0; i < opition.length; i++) {
			// isSelect[i] = false;
			// }
			// adapter = new MyAdapterCheckBox(this, mData);
			// result = "";
		} else if (v == deal_btn) {
			if (line_person.getVisibility() == View.VISIBLE
					&& line_person2.getVisibility() == View.GONE) {

				if (TextUtils.isEmpty(task_nextperson.getText())) {
//					task_nextperson.setError("请选择处理人！");
//					task_nextperson.requestFocus();
					ToastHelp.showToast(this, "请选择处理人！");
				} else {
					String nextHandler = transactors + nextpersonguids1;
					HashMap<String, Object> map = new HashMap<String, Object>();

					for (int i = 0; i < 2; i++) {
						nextHandler = nextHandler.replaceAll(";;", ";");
						nextpersonguids2 = nextpersonguids2.replaceAll(";;",
								";");
					}

					map.put("zhusongrenguid", nextHandler);
					map.put("chaosongrenguid", nextpersonguids2);
					map.put("messageItemGuid", messageItemGuid);
					map.put("operatorGuid", operatorGuid);
					map.put("pviGuid", pviGuid);
					map.put("workItemGuid", workItemGuid);
					map.put("operationGuid", operationGuid);
					map.put("operateStatus", operateStatus);
					map.put("handleOpinion", task_opinion.getText().toString());
					map.put("transitionGuid", transitionGuid);
					map.put("typecode", typecode);
					showDialog_wait("正在处理");
					Task task = new ShouwenDealTask(this, map);
					MainService.addTask(task);
				}
			} else if (line_person.getVisibility() == View.VISIBLE
					&& line_person2.getVisibility() == View.VISIBLE) {

				if (operateStatus.equals("2")) {
					if (TextUtils.isEmpty(task_nextperson.getText())
							&& TextUtils.isEmpty(task_nextperson2.getText())) {
						ToastHelp.showToast(this, "请至少选择一个下一步处理人！");
					} else {
						dealGongWen();
					}
				} else {
					dealGongWen();
				}
			} else if (line_person.getVisibility() == View.GONE
					&& line_person2.getVisibility() == View.GONE) {
				dealGongWen();
			}
		}
	}

	/**
	 * @author lilin
	 * @date 2012-8-3 下午2:34:08
	 * @annotation
	 */
	private void dealGongWen() {

		String nextHandler = transactors + nextpersonguids1;
		HashMap<String, Object> map = new HashMap<String, Object>();

		for (int i = 0; i < 2; i++) {
			nextHandler = nextHandler.replaceAll(";;", ";");
			nextpersonguids2 = nextpersonguids2.replaceAll(";;", ";");
		}

		map.put("zhusongrenguid", nextHandler);
		map.put("chaosongrenguid", nextpersonguids2);
		map.put("messageItemGuid", messageItemGuid);
		map.put("operatorGuid", operatorGuid);
		map.put("pviGuid", pviGuid);
		map.put("workItemGuid", workItemGuid);
		map.put("operationGuid", operationGuid);
		map.put("operateStatus", operateStatus);
		map.put("handleOpinion", task_opinion.getText().toString());
		map.put("transitionGuid", transitionGuid);
		map.put("typecode", typecode);
		showDialog_wait("正在处理");
		Task task = new ShouwenDealTask(this, map);
		MainService.addTask(task);

	}

	private int resumeType = 0;// 0其他恢复，1审批人1,2审批人2
	private String nextpersonnames1 = "";
	private String nextpersonguids1 = "";
	private String nextpersonnames2 = "";
	private String nextpersonguids2 = "";

	/* (non-Javadoc)
	 * @see com.epoint.mobileoa.bizlogic.SuperView#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		if (resumeType == 1) {
			String[] info = StringHelp
					.dealChooseListToString(PersonChooseViewNew.clist);
			nextpersonnames1 = info[0];
			nextpersonguids1 = info[1];
			task_nextperson.setText(nextpersonnames1);
		} else if (resumeType == 2) {
			String[] info = StringHelp
					.dealChooseListToString(PersonChooseViewNew.clist);
			nextpersonnames2 = info[0];
			nextpersonguids2 = info[1];
			task_nextperson2.setText(nextpersonnames2);
		}
		selectOpinionText = "";
	
	}

	/* (non-Javadoc)
	 * @see com.epoint.mobileoa.bizlogic.SuperView#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		PersonChooseViewNew.initData();
	}

	/**
	 * @author lilin
	 * @date 2012-6-6 下午4:13:07
	 * @annotation
	 */
	private void showOpinion() {
		if (commonopition != null && personopition != null) {
			opinionMenu();
		} else if (commonopition != null && personopition == null) {
			showPublicOpinionDialog(0);
		} else if (commonopition == null && personopition != null) {
			showPublicOpinionDialog(1);
		} else {
			ToastHelp.showToast(this, "您的意见模版为空！");
		}
	}

	/**
	 * @author lilin
	 * @date 2012-5-10 下午10:24:03
	 * @annotation
	 */
	private void opinionMenu() {
		String handleItems[] = { "公共模版", "个人模版" };
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(R.drawable.epoint2);
		builder.setTitle("意见模版");
		builder.setItems(handleItems, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					showPublicOpinionDialog(0);
					break;
				case 1:
					showPublicOpinionDialog(1);
					break;
				default:
					break;
				}
			}

		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();

	}

	private void showPublicOpinionDialog(final int opiniontype) {
		String title = "";
		mData.clear();
		if (opiniontype == 0) {
			title = "公共意见模版";
			isSelectOpition = new boolean[commonopition.length];
			Map<String, Object> map = new HashMap<String, Object>();
			for (int i = 0; i < commonopition.length; i++) {
				map = new HashMap<String, Object>();
				map.put("title", commonopition[i]);
				mData.add(map);
			}
			for (int i = 0; i < commonopition.length; i++) {
				isSelectOpition[i] = false;
			}
		} else if (opiniontype == 1) {
			title = "个人意见模版";
			isSelectOpition = new boolean[personopition.length];
			Map<String, Object> map1 = new HashMap<String, Object>();
			for (int i = 0; i < personopition.length; i++) {
				map1 = new HashMap<String, Object>();
				map1.put("title", personopition[i]);
				mData.add(map1);
			}
			for (int i = 0; i < personopition.length; i++) {
				isSelectOpition[i] = false;
			}
		}
		opitionTemplateAdp = new OpitionTemplateAdp(ProgressTaskDealView.this,
				mData);
		LayoutInflater inflater = LayoutInflater.from(this);// 渲染器
		View customdialog2view = inflater.inflate(R.layout.customdialog2, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(R.drawable.epoint2);
		builder.setTitle(title);
		builder.setView(customdialog2view);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					for (int i = 0; i < isSelectOpition.length; i++) {
						if (isSelectOpition[i]) { // 如果该选项被选中
							if (opiniontype == 0) {
								selectOpinionText = selectOpinionText
										+ commonopition[i] + "、";
							} else if (opiniontype == 1) {
								selectOpinionText = selectOpinionText
										+ personopition[i] + "、";
							}
						}
					}
					Log.i("andli", "所选意见内容：" + selectOpinionText);

					if (!TextUtils.isEmpty(task_opinion.getText().toString()
							.trim())) {
						String textString = task_opinion.getText().toString()
								.trim();
						String textString2 = textString
								+ "、"
								+ selectOpinionText.substring(0,
										selectOpinionText.length() - 1);
						task_opinion.setText(textString2);
					} else {
						task_opinion.setText(selectOpinionText.substring(0,
								selectOpinionText.length() - 1));
					}
					selectOpinionText = "";
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		builder.setNegativeButton("取消", null);
		ListView listView = (ListView) customdialog2view.findViewById(R.id.lv);
		listView.setAdapter(opitionTemplateAdp);
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				ViewHolder vHollder = (ViewHolder) arg1.getTag();// 在每次获取点击的item时将对于的checkbox状态改变，同时修改map的值。
				vHollder.cBox.toggle();// 反转当前视图的选中状态
				if (vHollder.cBox.isChecked() == true) {
					isSelectOpition[arg2] = true;
				} else {
					isSelectOpition[arg2] = false;
				}
				OpitionTemplateAdp.isSelected.put(arg2,
						vHollder.cBox.isChecked());
			}
		});
		opinionsDialog = builder.create();
		opinionsDialog.show();
	}

	/**
	 * @author lilin
	 * @date 2012-5-10 下午4:42:19
	 * @annotation 获取意见模版内容
	 */
	private void doTask_GetOpinion() {
		top_pb.setVisibility(View.VISIBLE);
		Task task = new OpinionTask(this, null);
		MainService.addTask(task);
		top_pb.setVisibility(View.VISIBLE);
	}

	@Override
	public void refreshForNewTask(int TaskId,Object... param) {
	}

}
